package net.wenku8.reader.api

import android.util.Log
import com.alibaba.fastjson2.JSON
import net.wenku8.reader.entity.ApiResult
import net.wenku8.reader.enums.StatusCode
import net.wenku8.reader.state.StateLogin
import net.wenku8.reader.util.isInt
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi


class Wenku8Connect{

    companion object {

        private const val URL = "http://app.wenku8.com/android.php"

        @OptIn(ExperimentalEncodingApi::class)
        fun request(param : Map<String, String>) : ApiResult<String> {
            Log.i("ApiConnect req:", JSON.toJSONString(param))
            try {
                val request = param.entries.joinToString("&") { (name, value) -> "$name=$value" }
                val formBuilder = FormBody.Builder()
                formBuilder.add("appver", "2.0")
                formBuilder.add("request", Base64.encode(request.toByteArray()))
                formBuilder.add("timetoken", System.currentTimeMillis().toString())
                val reqBuilder = Request.Builder().url(URL)
                val isLogin = param["action"] == "login" || param["action"] == "loginemail"
                if (!isLogin){
                    if (StateLogin.sessionId.value.trim().isEmpty()){
                        return ApiResult.fail("服务器请求失败:用户未登陆")
                    }else{
                        reqBuilder.addHeader("Cookie", "PHPSESSID=" + StateLogin.sessionId.value )
                    }
                }
                reqBuilder.post(formBuilder.build())
                val clientBuilder = OkHttpClient.Builder()
                clientBuilder.hostnameVerifier { _, _ -> true }
                val resp = clientBuilder.build().newCall(reqBuilder.build()).execute()
                if (resp.code != 200){
                    Log.i("ApiConnect request resp.code", resp.code.toString())
                    return ApiResult.fail("服务器请求失败:"+resp.code)
                }
                val respBody = resp.body?: return ApiResult.fail("返回数据为空")
                if ("avatar" == param["action"]){
                    return ApiResult.success(Base64.encode(resp.body!!.bytes()))
                }
                val body = respBody.string()
                if (body.length > 200){
                    Log.i("ApiConnect resp.body.substring:", body.substring(0, 200))
                }else{
                    Log.i("ApiConnect resp.body:", body)
                }
                if (isInt(body)){
                    val status = body.toInt()
                    if(status == 1){
                        if (isLogin){
                            val session = resp.headers("set-cookie")[0]
                            Log.i("ApiConnect session:", session)
                            if (session.length >= 42){
                                val sessionId = session.substring(10, 42)
                                return ApiResult.success(sessionId)
                            }else{
                                return ApiResult.fail("服务器请求失败:返回数据错误")
                            }
                        }
                        return ApiResult.success(body)
                    }else{
                        return ApiResult.fail(StatusCode.getErrorMsg(status))
                    }
                }
                return ApiResult.success(body)
            }catch (e : Exception){
                Log.e("", "服务器请求失败", e)
                return ApiResult.fail("服务器请求失败")
            }
        }

        fun getImage(url : String) : ApiResult<ByteArray> {
            try {
                val request = Request.Builder().url(url).get().build()
                val clientBuilder = OkHttpClient.Builder()
                clientBuilder.hostnameVerifier { _, _ -> true }
                val resp = clientBuilder.build().newCall(request).execute()
                if (resp.code != 200){
                    return ApiResult.fail("服务器请求失败")
                }
                return ApiResult.success(resp.body!!.bytes())
            }catch (e : Exception){
                Log.e("", "服务器请求失败", e)
                return ApiResult.fail("服务器请求失败")
            }
        }

    }


}